from django.shortcuts import render
from rest_framework.views import APIView
from DXdjango.utils.alipaysdk import AliPaySDK
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from coupon.models import CouponLogModel
from order.models import OrderModel
from django.db import transaction
import datetime
# Create your views here.


class IndexView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        order_id = request.data.get('order_id')
        # orderId = request.data.get('orderId')
        pay_price = request.data.get('pay_price')
        print(order_id, pay_price)
        alipay = AliPaySDK()
        link = alipay.page_pay(out_trade_no=order_id, total_amount=pay_price, subject='测试订单')
        print(link)
        return Response(link)

class ResultView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        data = request.GET.dict()
        print(data)
        alipay = AliPaySDK()
        result = alipay.check_sign(data)
        print(result)
        if not result:
            return Response('验签失败')
        time = datetime.datetime.now()
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                order_id = data.get('out_trade_no')
                user_id = request.user.id
                redis_conn = get_redis_connection('order')
                order_key = f'{user_id}:{order_id}'
                if redis_conn.exists(order_key):
                    redis_conn.hset(order_key, 'pay_status', 1)
                    redis_conn.hset(order_key, 'pay_time', time.strftime("%Y-%m-%d %H:%M:%S"))
                coupon_id = redis_conn.hget(order_key, 'coupon_id').decode()
                coupon = CouponLogModel.objects.get(id=coupon_id)
                coupon.use_status = 1
                coupon.use_time = time
                coupon.save()
                order_id = redis_conn.hget(order_key, 'order').decode()
                order = OrderModel.objects.get(id=order_id)
                order.pay_status = 1
                order.pay_time = time
                order.save()
                coupon_conn = get_redis_connection('coupon')
                if coupon_conn.exists(f'{user_id}:{coupon_id}'):
                    coupon_conn.delete(f'{user_id}:{coupon_id}')
            except Exception as e:
                transaction.savepoint_rollback(save_point)
                raise e
        return Response('支付成功')









